﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.IO;

namespace BootyShaker
{
    public partial class MainPage : PhoneApplicationPage
    {
        private PhotoChooserTask photoChooserTask;
        private CameraCaptureTask cameraCaptureTask;


        //AdRotator.AdRotatorControl AdRotatorControl;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            photoChooserTask = new PhotoChooserTask();
            photoChooserTask.Completed +=
            new EventHandler<PhotoResult>(PhotoChooserTaskCompleted);
            cameraCaptureTask = new CameraCaptureTask();
            cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCapture_Completed);



            App.shakeObjects = new List<ShakeObjectCtl>();
            if (App.IsTrial)
            {
                AdDuplex.IsEnabled = true;
                AdDuplex.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                AdDuplex.IsEnabled = false;
                AdDuplex.Visibility = System.Windows.Visibility.Collapsed;
            }

        }
    
        void cameraCapture_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                BitmapImage bitmap = new BitmapImage();
                bitmap.SetSource(e.ChosenPhoto);
                WriteableBitmap picLibraryImage = new WriteableBitmap(bitmap);
                App.currentShaker = new Shaker();
                App.currentShaker.shakeImage = picLibraryImage;

                Dispatcher.BeginInvoke(() =>
                {
                    this.NavigationService.Navigate(new Uri("/ShakeDesigner.xaml", UriKind.Relative));
                });
            }
        }

        private void PhotoChooserTaskCompleted(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                BitmapImage bitmap = new BitmapImage();
                bitmap.SetSource(e.ChosenPhoto);
                WriteableBitmap picLibraryImage = new WriteableBitmap(bitmap);
                App.currentShaker = new Shaker();
                App.currentShaker.shakeImage = picLibraryImage;

                Dispatcher.BeginInvoke(() =>
                {
                    this.NavigationService.Navigate(new Uri("/ShakeDesigner.xaml", UriKind.Relative));
                });
            }

        }
        List<HubTile> HtList = new List<HubTile>();
        private void LoadFilesThread()
        {


            if (App.IsExit) return;

            CopySamples();

            Dispatcher.BeginInvoke(() =>
           {
               overlayLoading.Visibility = System.Windows.Visibility.Visible;
               TileGrid.Visibility = System.Windows.Visibility.Collapsed;
           });
            string[] files;
            using (IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                files = myStore.GetFileNames("*.shk");
            }
            Dispatcher.BeginInvoke(() =>
            {
                TileGrid.RowDefinitions.Clear();
                TileGrid.Children.Clear();
                HtList.Clear();
            });

            foreach (string file in files)
            {

                try
                {
                    Shaker.GetPreviewImage(file);
                }
                catch (Exception ex)
                {
                    // myStore.DeleteFile(file);
                }



            }
            Dispatcher.BeginInvoke(() =>
            {
                int col = 0;
                int row = -1;

                foreach (string file in files)
                {
                    try
                    {

                        BitmapImage bi = new BitmapImage();
                        bi.CreateOptions = BitmapCreateOptions.BackgroundCreation;
                        bi.ImageOpened += new EventHandler<RoutedEventArgs>(bmp_ImageOpened);
                        bi.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(bmp_ImageFailed);

                        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                        {

                            using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(App.thumbPath + "\\" + Path.GetFileNameWithoutExtension(file) + ".jpg", FileMode.Open, FileAccess.Read))
                            {
                                bi.SetSource(fileStream);

                            }
                        }


                        if (col % 2 == 0)
                        {

                            RowDefinition rd = new RowDefinition();
                            TileGrid.RowDefinitions.Add(rd);

                            col = 0;
                            row++;
                        }

                        HubTile ht = new HubTile();
                        ht.Title = Path.GetFileNameWithoutExtension(file);

                        ht.Margin = CameraTile.Margin;
                        ht.Background = CameraTile.Background;
                        ht.GroupTag = CameraTile.GroupTag;

                        //Shaker.GetPreviewImage(file);


                        ht.Source = bi;
                        ht.UpdateLayout();



                        ht.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(ht_Tap);
                        ht.Tag = file;
                        ht.FontSize = 10;
                        ht.FontStretch = FontStretches.UltraCondensed;
                        HtList.Add(ht);
                        AddContextMenuWithMenuItems(ht);

                        TileGrid.Children.Add(ht);
                        Grid.SetColumn(ht, col);
                        Grid.SetRow(ht, row);
                        col++;


                    }
                    catch (Exception ex)
                    {
                        // myStore.DeleteFile(file);
                    }

                }

                overlayLoading.Visibility = System.Windows.Visibility.Collapsed;
                TileGrid.Visibility = System.Windows.Visibility.Visible;
            });
            App.LoadNeeded = false;

        }
        void bmp_ImageOpened(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("opened");
        }

        void bmp_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            Debug.WriteLine(e.ErrorException.Message);
        }

        private void LoadFiles()
        {
            if (!App.LoadNeeded) return;
            System.Threading.Thread startupThread = new System.Threading.Thread(new System.Threading.ThreadStart(LoadFilesThread));
            startupThread.Start();

            //System.Threading.Thread t = new System.Threading.Thread(LoadFilesThread);
            //t.Start();

        }
        private void CopySamples()
        {
            lock (App.operationSyncLock)
            {
                if (IsolatedStorageSettings.ApplicationSettings.Contains("AppLaunchCount"))
                {
                    var count = (int)IsolatedStorageSettings.ApplicationSettings["AppLaunchCount"];
                    count++;
                    IsolatedStorageSettings.ApplicationSettings["AppLaunchCount"] = count;
                }
                else
                {
                    try
                    {
                        Utils.Util.CopyFromContentToStorage("files/Sample1.shk");
                        // Utils.Utils.CopyFromContentToStorage("files/keira.shk");
                        Utils.Util.CopyFromContentToStorage("files/Sample2.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled000.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled001.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled002.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled003.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled004.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled005.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled006.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled007.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled008.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled009.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled010.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled011.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled012.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled013.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled014.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled015.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled016.shk");
                        //Utils.Util.CopyFromContentToStorage("files/untitled017.shk");

                    }
                    catch { }

                    IsolatedStorageSettings.ApplicationSettings.Add("AppLaunchCount", 0);
                    //string[] files = System.IO.Directory.GetFileNames("*.shk");
                }
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }
        ContextMenu contextMenu;
        private void AddContextMenuWithMenuItems(HubTile ht)
        {
            contextMenu = new ContextMenu();
            MenuItem menuItemDelete = new MenuItem() { Header = "Delete", Tag = "Delete" };
            menuItemDelete.Click += new RoutedEventHandler(menuItemDelete_Click);
            contextMenu.Items.Add(menuItemDelete);
            menuItemDelete.Tag = ht;
            ContextMenuService.SetContextMenu(ht, contextMenu);

        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

            if (App.IsTrial)
            {
                btnBuy.Visibility = System.Windows.Visibility.Visible;
                txtBuy.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                btnBuy.Visibility = System.Windows.Visibility.Collapsed;
                txtBuy.Visibility = System.Windows.Visibility.Collapsed;
            }

            //Dispatcher.BeginInvoke(() =>
            //{
            LoadFiles();
            if (App.IsTrial)
            {
                AdDuplex.IsEnabled = true;
                AdDuplex.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                AdDuplex.IsEnabled = false;
                AdDuplex.Visibility = System.Windows.Visibility.Collapsed;
            }
            UnFreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");

            //});
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            
            FreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");
        }
        private void FreezeHubTiles()
        {
            if (!CameraTile.IsFrozen) CameraTile.IsFrozen = true;
            if (!GalleryTile.IsFrozen) CameraTile.IsFrozen = true;
            foreach (HubTile ht in HtList)
            {
                if (!ht.IsFrozen) ht.IsFrozen = true;
            }
        }
        private void UnFreezeHubTiles()
        {
            if (CameraTile.IsFrozen) CameraTile.IsFrozen = false;
            if (GalleryTile.IsFrozen) CameraTile.IsFrozen = false;
            foreach (HubTile ht in HtList)
            {
                if (ht.IsFrozen) ht.IsFrozen = false;
            }
        }
        private void OpenCamera(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");
            cameraCaptureTask.Show();

        }

        private void OpenGallery(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");
            photoChooserTask.Show();
        }
        private void ht_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            showProgresBar();
            FreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");
            try
            {
                App.currentShaker = Shaker.Load((string)((HubTile)sender).Tag);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Oops, something went wrong! I'm not sure I can handle this one.", "Sorry, Mike", MessageBoxButton.OK);
                //var myStore = IsolatedStorageFile.GetUserStoreForApplication();
                //myStore.DeleteFile((string)((HubTile)sender).Tag);
                hideProgresBar();
                UnFreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");
                return;
            }
            hideProgresBar();
            Dispatcher.BeginInvoke(() =>
            {
                this.NavigationService.Navigate(new Uri("/ShakeDesigner.xaml", UriKind.Relative));
            });
        }

        void showProgresBar() { progressBar.Visibility = System.Windows.Visibility.Visible; }
        void hideProgresBar() { progressBar.Visibility = System.Windows.Visibility.Collapsed; }
        private void menuItemDelete_Click(object sender, RoutedEventArgs e)
        {
            showProgresBar();
            var myStore = IsolatedStorageFile.GetUserStoreForApplication();
            HubTile ht = (HubTile)((MenuItem)sender).Tag;
            myStore.DeleteFile((string)ht.Tag);
            App.LoadNeeded = true;
            LoadFiles();
            hideProgresBar();

        }


        private void btnRate_Click(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");
            MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
            marketplaceReviewTask.Show();
        }

        private void btnBuy_Click(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");
            //Show an application, using the default ContentType.
            MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
            marketplaceDetailTask.ContentIdentifier = "740b92a7-39e3-4db5-94ec-5ddcff342cec";
            marketplaceDetailTask.Show();
        }

        private void btnAbout_Click(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");

            Dispatcher.BeginInvoke(() =>
            {
                //this.NavigationService.Navigate(new Uri("/HelpPage.xaml", UriKind.Relative));
                this.NavigationService.Navigate(new Uri("/AboutPage.xaml", UriKind.Relative));
            });
        }
        private void btnFacebook_Click(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask webbrowser = new WebBrowserTask();
            webbrowser.Uri = new Uri("http://www.facebook.com/VincentsBootyShaker");
            webbrowser.Show();
        }

        private void imgHelp_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FreezeHubTiles();//HubTileService.FreezeGroup("MenuTiles");

            Dispatcher.BeginInvoke(() =>
            {
                //this.NavigationService.Navigate(new Uri("/HelpPage.xaml", UriKind.Relative));
                this.NavigationService.Navigate(new Uri("/HelpPage.xaml", UriKind.Relative));
            });
        }

    }
}
